import React, { useState, useRef, useCallback } from "react";
import {
  View,
  StyleSheet,
  ActivityIndicator,
  BackHandler,
  SafeAreaView,
} from "react-native";
import { Stack } from "expo-router";
import { WebView } from "react-native-webview";
import { useTheme } from "@/contexts/ThemeContext";
import { getHeaderStyle } from "@/styles/header.style";
import { useFocusEffect } from "@react-navigation/native";

// AI助手URL配置
const AI_ASSISTANT_URL = "https://beloved.ltd:5000/";

export default function AIAssistantScreen() {
  // 获取当前主题模式
  const { themeMode } = useTheme();
  const isDark = themeMode === "dark";

  // 获取基于当前主题的header样式
  const headerStyles = getHeaderStyle(themeMode);

  // 根据主题设置颜色
  const backgroundColor = isDark ? "#15202B" : "#FFFFFF";
  const primaryColor = "#1976D2";

  // WebView状态
  const [isLoading, setIsLoading] = useState(true);
  const [canGoBack, setCanGoBack] = useState(false);

  // WebView引用
  const webViewRef = useRef(null);

  // 处理Android返回按钮
  useFocusEffect(
    useCallback(() => {
      const onBackPress = () => {
        if (canGoBack && webViewRef.current) {
          webViewRef.current.goBack();
          return true;
        }
        return false;
      };

      BackHandler.addEventListener("hardwareBackPress", onBackPress);
      return () =>
        BackHandler.removeEventListener("hardwareBackPress", onBackPress);
    }, [canGoBack])
  );

  return (
    <>
      <Stack.Screen
        options={{
          title: "AI助手",
          headerTitleAlign: headerStyles.headerTitleAlign as "left" | "center",
          headerStyle: headerStyles.headerStyle,
          headerTintColor: headerStyles.headerTintColor,
          headerTitleStyle: headerStyles.headerTitleStyle,
        }}
      />
      <SafeAreaView style={[styles.container, { backgroundColor }]}>
        {/* WebView */}
        <WebView
          ref={webViewRef}
          source={{ uri: AI_ASSISTANT_URL }}
          style={styles.webView}
          onLoadStart={() => setIsLoading(true)}
          onLoadEnd={() => setIsLoading(false)}
          onNavigationStateChange={(navState) => {
            setCanGoBack(navState.canGoBack);
          }}
          javaScriptEnabled={true}
          domStorageEnabled={true}
          startInLoadingState={true}
          renderLoading={() => (
            <View style={styles.loadingContainer}>
              <ActivityIndicator size="large" color={primaryColor} />
            </View>
          )}
        />

        {/* 加载指示器 */}
        {isLoading && (
          <View style={styles.loadingOverlay}>
            <ActivityIndicator size="large" color={primaryColor} />
          </View>
        )}
      </SafeAreaView>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  webView: {
    flex: 1,
  },
  loadingContainer: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    alignItems: "center",
    justifyContent: "center",
  },
  loadingOverlay: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "rgba(0,0,0,0.3)",
    alignItems: "center",
    justifyContent: "center",
  },
});
